package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        if(!RegexUtils.isPhoneInvalid(phone)){
            //生成验证码
            String randomNumbers = RandomUtil.randomNumbers(6);

            //存入到session中
            session.setAttribute(phone,randomNumbers);
            //发送验证码成功
            log.debug("发送短信验证码成功，验证码：{}",randomNumbers);
            return Result.ok();
        }else {
            return Result.fail("手机号不合法！");
        }
    }

    /**
     * 登陆
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //3. 进行校验验证码
        String code = (String) session.getAttribute(phone);
        if (StrUtil.isNotEmpty(code) &&code.equals(loginForm.getCode()) ){
            //相等 根据手机号查询用户
            User user = query().eq("phone", phone).one();
            //判断用户是否存在
            if(user == null ){
                //用户不存在 则 创建用户
                user =  createUserWithPhone(phone);
            }
            //保存用户信息到redis中
            UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
            //.将User对象转为HashMap存储
            Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                    CopyOptions.create()
                            .setIgnoreNullValue(true)
                            .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
            //存储
            String token = UUID.randomUUID().toString(true);
            String tokenKey = LOGIN_USER_KEY + token;
            stringRedisTemplate.opsForHash().putAll(tokenKey ,userMap);
            //设置token有效期
            stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.SECONDS);
            return Result.ok(token);
        }else {
            return Result.fail("验证码错误！");
        }
    }

    /**
     * 创建用户
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        User user = new User().setPhone(phone);
        if( this.save(user)){
            return user;
        }
        return null;
    }

    /**
     * 生成tokens
     * @return
     */
    @Override
    public Result tokens() {
        String tokens = "";
        List<User> list = this.list();
        for (User user : list) {
            //保存用户信息到redis中
            UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
            //.将User对象转为HashMap存储
            Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                    CopyOptions.create()
                            .setIgnoreNullValue(true)
                            .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
            String token = UUID.randomUUID().toString(true);
            String tokenKey = LOGIN_USER_KEY + token;
            stringRedisTemplate.opsForHash().putAll(tokenKey ,userMap);
            //设置token有效期
            stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.SECONDS);
            tokens += token +",";
        }
        return Result.ok(tokens);
    }
}
